package com.cssw.fyzb.busi.api.system;

import com.cssw.fyzb.busi.cache.Cache;
import com.cssw.fyzb.busi.cache.CacheKeys;
import com.cssw.fyzb.busi.cache.Fetcher;
import com.cssw.fyzb.busi.convert.Converter;
import com.cssw.fyzb.core.model.vo.system.SdkInfoVo;
import com.cssw.fyzb.busi.service.system.SysParamService;
import com.cssw.fyzb.busi.util.TxDes;
import com.cssw.fyzb.core.model.dodb.SysParam;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Feng Chen
 */
@Function(description = "获取腾讯sdk信息",
        parameters = {
                @Parameter(name = "force", type = Type.Boolean, description = "强制刷新缓存，true - 是, false - 否", required = false),
        },
        result = @Result(
                properties = {
                        @Property(name = "secretId", type = Type.String, description = "APP标识"),
                        @Property(name = "secretKey", type = Type.String, description = "APP密钥"),
                }
        ))
@Component
public class GetSdkInfo implements Action {

    @Autowired
    private SysParamService sysParamService;

    @Value("${sdk.desKey:xykj@2020}")
    private String desKey;

    private static final String SDK = "TXSDK";

    private static final Logger logger = LoggerFactory.getLogger(GetSdkInfo.class);

    @Override
    public Response execute(Request request) throws Exception {
        try {

            Boolean force = request.getBoolean("force");

            // 获取参数
            SysParam sysParam = Cache.get(CacheKeys.paramKey(SDK), new Fetcher<SysParam>() {
                @Override
                public SysParam fetch() {
                    return sysParamService.findByCode(SDK);
                }
            }, force);

            // 转换参数
            SdkInfoVo data = ((Converter<SysParam, SdkInfoVo>) p -> {
                SdkInfoVo vo = null;
                if (p != null) {
                    try {
                        vo = new SdkInfoVo();
                        vo.setInfo(TxDes.encrypt(desKey, p.getParamValue()));
                    } catch (Exception e) {
                        logger.error("", e);
                    }
                }
                return vo;
            }).convert(sysParam);

            return Response.success().put("data", data);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("操作异常");
        }
    }

}
